package com.party.admin.web.controller.mall;

import com.google.common.collect.Maps;
import com.party.admin.biz.mall.MallGoodsBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.input.mall.MallGoodsInput;
import com.party.admin.web.dto.output.mall.MallGoodsOutput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.mall.*;
import com.party.core.service.mall.IMallBrandService;
import com.party.core.service.mall.IMallCategoryService;
import com.party.core.service.mall.IMallGoodsService;
import com.party.core.service.mall.IMallProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 商城商品控制器
 * Created by wei.li
 *
 * @date 2017/8/16 0016
 * @time 9:57
 */

@Controller
@RequestMapping(value = "/mall/goods")
public class MallGoodsController {
    @Autowired
    private IMallGoodsService mallGoodsService;
    @Autowired
    private MallGoodsBizService mallGoodsBizService;
    @Autowired
    private IMallProductService mallProductService;
    @Autowired
    private IMallBrandService mallBrandService;
    @Autowired
    private IMallCategoryService mallCategoryService;
    @Resource(name = "transactionManager")
    private DataSourceTransactionManager transactionManager;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 商城商品列表
     *
     * @param goods
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView list(MallGoods goods, Page page, CommonInput commonInput, String categoryId, String brandId) {
        page.setLimit(20);
        goods.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        params.put("categoryId", categoryId);
        params.put("brandId", brandId);
        ModelAndView modelAndView = new ModelAndView("mall/goods/goodsList");
        List<MallGoodsOutput> list = mallGoodsBizService.list(goods, params, page);

        List<MallBrand> brandList = mallBrandService.list(new MallBrand());
        Map<String, String> brands = Maps.newHashMap();
        brandList.forEach(brand -> brands.put(brand.getId(), brand.getName()));

        List<MallCategoryOutput> categoryList = mallCategoryService.getAll();

        modelAndView.addObject("categoryId", categoryId);
        modelAndView.addObject("categoryList", categoryList);
        modelAndView.addObject("brandId", brandId);
        modelAndView.addObject("brandList", brands);
        modelAndView.addObject("input", commonInput);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("goods", goods);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("getGoodsList")
    public Map<String, Object> getGoodsList(MallGoods goods, Page page, CommonInput commonInput) {
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<MallGoodsOutput> list = mallGoodsBizService.list(goods, params, page);
        Map<String, Object> ret = Maps.newHashMap();
        ret.put("data", list);
        ret.put("count", page.getTotalCount());
        ret.put("code", 0);
        return ret;
    }


    /**
     * 查看商城商品
     *
     * @param id 编号
     * @return 交互数据
     */
    @RequestMapping(value = "view")
    public ModelAndView view(String id, String brandId) {
        ModelAndView modelAndView = new ModelAndView("mall/goods/goodsView");
        if (StringUtils.isNotEmpty(id)) {
            Map<String, Object> modelResult = mallGoodsBizService.goodsView(id);
            modelAndView.addAllObjects(modelResult);
        }
        List<MallBrand> goodsBrands = mallBrandService.list(new MallBrand());
        modelAndView.addObject("goodsBrands", goodsBrands);
        modelAndView.addObject("brandId", brandId);
        return modelAndView;
    }


    /**
     * 保存商城商品
     *
     * @param mallGoods 商城商品
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(MallGoodsInput mallGoods, BindingResult result, MallGoodsDetail goodsDetail) {
        try {
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                return AjaxResult.error(description);
            }
            mallGoodsBizService.saveGoodsBiz(mallGoods, goodsDetail);
            return AjaxResult.success((Object) mallGoods.getId());
        } catch (BusinessException e) {
            logger.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.success(e.getMessage());
        } catch (Exception e) {
            logger.error("保存商品异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 逻辑删除商城商品
     *
     * @param goodsId 商品id
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "deleteGoods", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult deleteGoods(String goodsId) {
        if (StringUtils.isEmpty(goodsId)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            boolean result = mallGoodsBizService.deleteGoods(goodsId);
            if (result) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (BusinessException e) {
            return AjaxResult.error(e.getMessage() + "，不能删除");
        }
    }

    /**
     * 批量删除商品
     *
     * @param ids: 商品的id(用','隔开)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "batchDelete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult batchDelete(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error("ids不能为空");
        }
        String[] idList = ids.split(",");
        for (int i = 0; i < idList.length; i++) {
            String id = idList[i];
            MallGoods mallGoods = mallGoodsService.get(id);
            try {
                //逻辑代码，可以写上你的逻辑处理代码
                boolean result = mallGoodsBizService.deleteGoods(id);
                if (!result) {
                    return AjaxResult.error("商品：" + mallGoods.getName() + "不能删除");
                }
            } catch (BusinessException be) {
                logger.error("商品：" + mallGoods.getName() + be.getMessage());
                return AjaxResult.error("商品：" + mallGoods.getName() + be.getMessage() + "，不能删除");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 逻辑删除产品
     *
     * @param productId 产品id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteProduct")
    public AjaxResult deleteProduct(String productId) {
        if (StringUtils.isEmpty(productId)) {
            return AjaxResult.error("id不能为空");
        }
        mallProductService.deleteLogic(productId);
        return AjaxResult.success();
    }

    /**
     * 商品批量上架或下架
     *
     * @param goodsIds 商品IDS
     * @param status   状态
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "upOrDown", method = RequestMethod.POST)
    public AjaxResult upOrDown(String goodsIds, Integer status) {
        if (StringUtils.isEmpty(goodsIds)) {
            return AjaxResult.error("商品id不能为空");
        }

        try {
            Integer count = 0;
            for (String goodsId : goodsIds.split(",")) {
                if (status.equals(MallGoods.STATUS_DOWN)) {
                    boolean flag = mallGoodsBizService.downGoods(goodsId);
                    if (!flag) {
                        count++;
                        continue;
                    }
                }
                MallGoods mallGoods = mallGoodsService.get(goodsId);
                mallGoods.setStatus(status);
                mallGoods.setOpenStartTime(null);
                mallGoods.setOpenEndTime(null);
                mallGoodsService.update(mallGoods);
            }
            String statusName = "";
            if (count > 0) {
                statusName += "，其中" + count + "件商品下架失败，存在待支付订单";
            }
            return AjaxResult.success(statusName);
        } catch (Exception e) {
            return AjaxResult.error("操作商品异常");
        }
    }

    /**
     * 复制
     *
     * @param goodsId 商品id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "copyGoods", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult copyGoods(String goodsId) {
        if (StringUtils.isEmpty(goodsId)) {
            return AjaxResult.error("商品id不能为空");
        }
        try {
            mallGoodsBizService.copyGoods(goodsId);
            return AjaxResult.success();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("复制商品异常", e);
            return AjaxResult.error("复制商品异常");
        }
    }

    /**
     * 选择商品
     *
     * @param page      分页参数
     * @param mallGoods 查询参数
     * @param isMulti   是否多选
     * @return
     */
    @RequestMapping("selectGoods")
    public ModelAndView selectGoods(Page page, MallGoods mallGoods, Boolean isMulti) {
        ModelAndView mv = new ModelAndView("/mall/goods/selectGoods");
        mallGoods.setStatus(MallGoods.STATUS_UP);
        mallGoods.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<MallGoods> mallGoodsList = mallGoodsService.listPage(mallGoods, page);
        mv.addObject("goodsList", mallGoodsList);
        mv.addObject("mallGoods", mallGoods);
        mv.addObject("isMulti", isMulti);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 选择分类商品
     *
     * @param page      分页参数
     * @param mallGoods 查询参数
     * @return
     */
    @RequestMapping("selectCategoryGoods")
    public ModelAndView selectCategoryGoods(Page page, MallGoods mallGoods) {
        ModelAndView mv = new ModelAndView("/mall/goods/selectCategoryGoods");
        List<MallCategoryWithGoods> mallCategoryWithGoods = mallGoodsService.withCategoryListPage(mallGoods, page);
        mv.addObject("list", mallCategoryWithGoods);
        mv.addObject("page", page);
        mv.addObject("mallGoods", mallGoods);
        return mv;
    }

    @ResponseBody
    @RequestMapping("reviseStock")
    public void reviseStock() {
        mallGoodsBizService.reviseStock();
    }
}
